package com.cremamobile.filemanager;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import java.util.Stack;

import com.cremamobile.filemanager.file.DeviceFileEntry;
import com.cremamobile.filemanager.file.DirFileEntry;
import com.cremamobile.filemanager.file.FileCopyer;
import com.cremamobile.filemanager.file.FileDeleter;
import com.cremamobile.filemanager.file.FileListEntry;
import com.cremamobile.filemanager.file.FileLister;
import com.cremamobile.filemanager.file.FileMover;
import com.cremamobile.filemanager.file.FileSorter;
import com.cremamobile.filemanager.file.FileUtils;
import com.cremamobile.filemanager.file.FileWorker;
import com.cremamobile.filemanager.file.FindHistory;
import com.cremamobile.filemanager.file.IconMap;
import com.cremamobile.filemanager.file.ResultCallbacks;
import com.cremamobile.filemanager.file.Exception.ExistSameFileNameException;
import com.cremamobile.filemanager.fileWoker.Lister;
import com.cremamobile.filemanager.gridview.FileListAdapter;
import com.cremamobile.filemanager.history.HistoryNode;
import com.cremamobile.filemanager.service.*;
import com.cremamobile.filemanager.settingview.SlideAnimationLayout;
import com.cremamobile.filemanager.utils.CLog;
//import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cremamobile.filemanager.IRemoteService;
import com.cremamobile.filemanager.IRemoteServiceCallback;
import com.cremamobile.filemanager.R;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

public class CremaActivity extends ActionBarActivity implements
	NavigationDrawerFragment.NavigationDrawerCallbacks {

		  
	public static final int BUTTON_ID_COPY = 1011;
	public static final int BUTTON_ID_MOVE = 1012;
	public static final int BUTTON_ID_RENAME = 1013;
	public static final int BUTTON_ID_NEW_FOLDER = 1014;
	public static final int BUTTON_ID_SORT = 1015;
	public static final int BUTTON_ID_SHARE = 1016;
	public static final int BUTTON_ID_REFRESH = 1017;
	public static final int BUTTON_ID_SETTING = 1018;
	
	public static final int WORK_MODE_NORMAL = 0;
	public static final int WORK_MODE_COPY = 1;
	public static final int WORK_MODE_MOVE = 2;
	public static final int WORK_MODE_DELETE = 3;
	public static final int WORK_MODE_RENAME = 4;
	public static final int WORK_MODE_SHARE = 5;
	public static final int WORK_MODE_PAUSE_COPY = 6;
	public static final int WORK_MODE_PAUSE_MOVE = 7;
	
	
	public static final int FAVORITE_MAX_SIZE = 10;
	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private static NavigationDrawerFragment mNavigationDrawerFragment;

	/**
	 * Used to store the last screen title. For use in
	 * {@link #restoreActionBar()}.
	 */
	private CharSequence mTitle;

	
	private static Stack<HistoryNode>  mHistoryStack;
	
	
	private static FileListEntry mCurrentPath;
	private static int mCurrentSelectedItem;
	private static int mWorkMode = WORK_MODE_NORMAL;
	private static int mViewMode;
	
	private static GridView	mMainGrid;
	private static ListView mMainList;
	
	private static FileListAdapter mFileAdapter;
	
	private final long FINISH_INTERVAL_TIME = 1000;
	private long backPressedTime = 0;
	
	private static List<FileListEntry> mSelectedItem;
	private static List<FileListEntry> mDeviceList;
	private static ViewGroup mBottomBarView;
	private static ViewGroup mPathTextView;
	private static HorizontalScrollView mPathTextViewScroller;
	private static Button mViewModeButton;
	private static Button mDeleteButton;
	private static Button mSettingButton;
	private static ImageView mDeviceImageView;
	private static ImageView mFavoriteImageView;
	
	private int mSortType = FileSorter.SORT_BY_NAME_ASC;
	private boolean mDirOnTop = true;
	private static boolean mIsRoot;
	private static boolean mIsFirstLoadFolder = true;
	private View mActionbarNormal;
	private View mActionbarWork;

	private static boolean mNeedUpdateNavigationDrawer = false;
	
	/**
	 * Option Menu ...
	 */
	private static SlideAnimationLayout settingView;
	private OnClickListener settingMenuClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			settingView.setVisibility(View.GONE);
			
			int id = v.getId();
			switch(id) {
			case R.id.setting_copy:
				sendEventTrakcer("Setting Click", "Copy");
				
				mWorkMode = WORK_MODE_COPY;
				setWorkMode(true);
				break;
			case R.id.setting_move:
				sendEventTrakcer("Setting Click", "Move");
				
				mWorkMode = WORK_MODE_MOVE;
				setWorkMode(true);
				break;
			case R.id.setting_rename:
				sendEventTrakcer("Setting Click", "Rename");

				mWorkMode = WORK_MODE_RENAME;
				setWorkMode(true);
				break;
			case R.id.setting_newfolder:
				sendEventTrakcer("Setting Click", "New Folder");

				setNewFolder();
				break;
			case R.id.setting_sort:
				sendEventTrakcer("Setting Click", "Sort");

				setSort();
				break;
			case R.id.setting_share:
				sendEventTrakcer("Setting Click", "Share");

				mWorkMode = WORK_MODE_SHARE;
				setWorkMode(true);
				break;
			case R.id.setting_refresh:
				sendEventTrakcer("Setting Click", "Refresh");

				refresh();
				break;
			case R.id.setting_setting:
				sendEventTrakcer("Setting Click", "Setting");

				setting_setting();
				break;
			}
		}
		
	};
	
	private void setNewFolder() {
		final CremaDialog dialog = new CremaDialog(this, CremaDialog.TYPE_INPUT, 
				getResources().getString(R.string.alert),
				getResources().getString(R.string.newfolder_dialog_message));
		dialog.setClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (v.getId() == R.id.button_confirm) {
					String newFolderName = dialog.getEditText();
					if (newFolderName == null || newFolderName.length() <= 0) {
						//TODO. alert!
						Toast.makeText(CremaActivity.this, R.string.toast_newfolder_notinput, Toast.LENGTH_SHORT).show();
						return;
					}
					
					try {
						FileUtils.createFolder(mCurrentPath.getAbsolutePath() + "/" + newFolderName);
						dialog.dismiss();
						
						refreshWithCurrentSelectedItem();
						
						mNavigationDrawerFragment.addChildNode(new DirFileEntry(new File(mCurrentPath.getAbsolutePath() + "/" + newFolderName)));
					} catch (ExistSameFileNameException e) {
						// TODO Auto-generated catch block
						Toast.makeText(CremaActivity.this, R.string.toast_newfolder_already_exist, Toast.LENGTH_SHORT).show();
					}
				} else {
					dialog.dismiss();
				}
			}
			
		});
		dialog.setEditText(getResources().getString(R.string.new_folder));
		dialog.show();
		
	}
	
	private void setSort() {
		CremaDialog dialog = new CremaDialog(this, CremaDialog.TYPE_SELECT_SORT,
			new OnClickListener() {
	
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int id = v.getId();
					switch(id) {
					case R.id.button_sortby_name:
						mSortType = FileSorter.SORT_BY_NAME_ASC;
						break;
					case R.id.button_sortby_filetype:
						mSortType = FileSorter.SORT_BY_EXT_ASC;
						break;
					case R.id.button_sortby_date:
						mSortType = FileSorter.SORT_BY_DATE_ASC;
						break;
					case R.id.button_sortby_size:
						mSortType = FileSorter.SORT_BY_SIZE_ASC;
						break;
					}
					
					refresh();
				}
				
				
			});
		switch(mSortType) {
		case FileSorter.SORT_BY_NAME_ASC:
			dialog.focusView(R.id.button_sortby_name);
			break;
		case FileSorter.SORT_BY_EXT_ASC:
			dialog.focusView(R.id.button_sortby_filetype);
			break;
		case FileSorter.SORT_BY_DATE_ASC:
			dialog.focusView(R.id.button_sortby_date);
			break;
		case FileSorter.SORT_BY_SIZE_ASC:
			dialog.focusView(R.id.button_sortby_size);
			break;
		}
		dialog.show();
	}
	
	private void setWorkMode(boolean selectMode) {
		mFileAdapter.setSelectMode(selectMode);
		changeActionbarWorkMode(mWorkMode);
	}
	
	private void changeActionbarWorkMode(int workMode) {
		ActionBar ab = getSupportActionBar();
		ab.setDisplayShowCustomEnabled(true);
		ab.setDisplayShowTitleEnabled(false);
		ab.setDisplayShowHomeEnabled(false);
		ab.setDisplayHomeAsUpEnabled(false);
		
		if (mActionbarWork == null)
			mActionbarWork = getLayoutInflater().inflate(R.layout.actionbar_working, null);
		ab.setCustomView(mActionbarWork);
		TextView titleView = (TextView) mActionbarWork.findViewById(R.id.actionbar_title);
		int resId = 0;
		switch (mWorkMode) {
		case WORK_MODE_COPY:
			resId = R.string.actionbar_title_copy;
			break;
		case WORK_MODE_MOVE:
			resId = R.string.actionbar_title_move;
			break;
		case WORK_MODE_DELETE:
			resId = R.string.actionbar_title_delete;
			break;
		case WORK_MODE_RENAME:
			resId = R.string.actionbar_title_rename;
			break;
		case WORK_MODE_PAUSE_COPY:
		case WORK_MODE_PAUSE_MOVE:
			resId = R.string.actionbar_title_pause;
			break;
		case WORK_MODE_SHARE:
			resId = R.string.actionbar_title_share;
			break;
		default:
			resId = R.string.app_name;
			break;
		}
		titleView.setText(getResources().getString(resId));
		
		Button doingButton = (Button) mActionbarWork.findViewById(R.id.actionbar_doing);
		Button allSelectButton = (Button) mActionbarWork.findViewById(R.id.actionbar_all_select);
		switch(mWorkMode) {
		case WORK_MODE_PAUSE_COPY:
		case WORK_MODE_PAUSE_MOVE:
			doingButton.setBackgroundResource(R.drawable.button_actionbar_pause);
			break;
		case WORK_MODE_COPY:
			doingButton.setBackgroundResource(R.drawable.button_actionbar_copy);
			break;
		case WORK_MODE_MOVE:
			doingButton.setBackgroundResource(R.drawable.button_actionbar_move);
			break;
		case WORK_MODE_DELETE:
			doingButton.setBackgroundResource(R.drawable.button_actionbar_delete);
			break;
		case WORK_MODE_RENAME:
			doingButton.setBackgroundResource(R.drawable.button_actionbar_rename);
			break;
		case WORK_MODE_SHARE:
			doingButton.setBackgroundResource(R.drawable.button_actionbar_share);
			break;
			
		}
		if (mWorkMode == WORK_MODE_PAUSE_COPY || mWorkMode == WORK_MODE_PAUSE_MOVE) {
			allSelectButton.setBackgroundResource(R.drawable.folder_01);
		} else {
			allSelectButton.setBackgroundResource(R.drawable.button_actionbar_all_select);
		}
	}
	
	public boolean checkBeforeWork(final FileWorker work) {
		List<FileListEntry> selectedList = mSelectedItem;

		if (selectedList == null) {
			// TODO Dialog
			return false;
		}
		
		boolean existFiles = FileUtils.checkExistFiles(work.getDestination(), selectedList);
		if (existFiles) {
			CremaDialog dialog = new CremaDialog(this, 
					((work.type() == FileWorker.FILE_COPYER) ? CremaDialog.TYPE_SELECT_COPY : CremaDialog.TYPE_SELECT_MOVE),
					new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							int id = v.getId();
							switch(id) {
							case R.id.button_all_file_replace:
								work.setMode(FileWorker.MODE_REPLACE);
								work.execute();
								break;
							case R.id.button_rename:
								work.setMode(FileWorker.MODE_RENAME);
								work.execute();
								break;
							case R.id.button_cancel:
								break;
							}
						}
				
			});
			dialog.show();
			return false;
		}
		return true;
	}
	
	public void copy() {
		List<FileListEntry> selectedList = mSelectedItem;

		ResultCallbacks cb = new ResultCallbacks() {

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				restoreActionBar();
				restoreBottomBarSize();
				mFileAdapter.setSelectMode(false);
				mSelectedItem.clear();				
			}

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
//				Toast.makeText(CremaActivity.this, R.string.toast_move_success, Toast.LENGTH_SHORT).show();
				restoreActionBar();
				restoreBottomBarSize();
				mFileAdapter.setSelectMode(false);
				mSelectedItem.clear();
				
				refreshWithCurrentSelectedItem();
			}

			@Override
			public void onFail(int failCode) {
				// TODO Auto-generated method stub
				
			}
			
		};
		
		FileCopyer copyer = new FileCopyer(getApplicationContext(), selectedList, mCurrentPath, cb);
		copyer.showWithActivity(this);
		if (checkBeforeWork(copyer))
			copyer.execute();
	}
	
	public void move() {
		List<FileListEntry> selectedList = mSelectedItem;
		
		ResultCallbacks cb = new ResultCallbacks() {

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				restoreActionBar();
				restoreBottomBarSize();
				mFileAdapter.setSelectMode(false);
				mSelectedItem.clear();				
			}

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
//				Toast.makeText(CremaActivity.this, R.string.toast_move_success, Toast.LENGTH_SHORT).show();
				restoreActionBar();
				restoreBottomBarSize();
				mFileAdapter.setSelectMode(false);
				mSelectedItem.clear();
				
				refreshWithCurrentSelectedItem();
			}

			@Override
			public void onFail(int failCode) {
				// TODO Auto-generated method stub
				
			}
			
		};
		
		FileMover mover = new FileMover(getApplicationContext(), selectedList, mCurrentPath, cb);
		mover.showWithActivity(this);
		if (checkBeforeWork(mover))
			mover.execute();
	}
	
	public void rename() {
		final CremaDialog dialog = new CremaDialog(this, CremaDialog.TYPE_INPUT, 
		getResources().getString(R.string.alert),
		getResources().getString(R.string.rename_dialog_message));
		dialog.setClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int id = v.getId();
				if (id == R.id.button_confirm) {
					String renameText = dialog.getEditText();
					boolean result = false;
					FileListEntry targetItem = (FileListEntry) mSelectedItem.get(0);
					try {
						result = FileUtils.rename(targetItem.getAbsolutePath(), targetItem.getRenameAbsolutePath(renameText));
						
						refreshWithCurrentSelectedItem();
					} catch (ExistSameFileNameException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						//TODO.
					}
					if (result ) {
						restoreActionBar();
						restoreBottomBarSize();
						mFileAdapter.setSelectMode(false);
						mSelectedItem.clear();
					} else {
						//TODO...
					}
				}
				dialog.dismiss();
			}
			
		});
		FileListEntry targetItem = (FileListEntry) mSelectedItem.get(0);
		dialog.setEditText(targetItem.getName());
		dialog.show();

	}
	
	public void delete() {
		List<FileListEntry> selectedList = mSelectedItem;
		
		if (selectedList == null) {
			// TODO Dialog
			return;
		}
		
		ResultCallbacks cb = new ResultCallbacks() {

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				restoreActionBar();
				restoreBottomBarSize();
				mFileAdapter.setSelectMode(false);
				mSelectedItem.clear();				
			}

			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
//				Toast.makeText(CremaActivity.this, R.string.toast_move_success, Toast.LENGTH_SHORT).show();
				restoreActionBar();
				restoreBottomBarSize();
				mFileAdapter.setSelectMode(false);
				mSelectedItem.clear();
				
				refreshWithCurrentSelectedItem();
			}

			@Override
			public void onFail(int failCode) {
				// TODO Auto-generated method stub
				restoreActionBar();
				restoreBottomBarSize();
				mFileAdapter.setSelectMode(false);
				mSelectedItem.clear();
				
				refreshWithCurrentSelectedItem();
			}
			
		};
		
		FileDeleter deleter = new FileDeleter(getApplicationContext(), selectedList, cb);
		deleter.showWithActivity(this);
		deleter.execute();		
	}
	
	public void share() {
		List<FileListEntry> selectedList = mSelectedItem;
		
		if (selectedList == null) {
			// TODO Dialog
			return;
		}

		Intent intent = new Intent(Intent.ACTION_SEND);
		File file = ((FileListEntry)selectedList.get(0)).getPath();
		
		Uri uri = Uri.fromFile(file);
		intent.setType("image/jpg");
		intent.putExtra(Intent.EXTRA_STREAM, uri);
		startActivity(Intent.createChooser(intent, "Choose"));
		
		// 성공 실패 여부를 알 수 없음. 그냥 Normal모드로 복귀
		restoreActionBar();
		restoreBottomBarSize();
		mFileAdapter.setSelectMode(false);
		mSelectedItem.clear();
		
		refreshWithCurrentSelectedItem();
	}
	
	public void refresh() {
		mCurrentSelectedItem = 0;
		gettingCurrentPathList(mCurrentPath, mCurrentSelectedItem, false, mIsRoot);
	}
	
	public void refreshWithCurrentSelectedItem() {
		gettingCurrentPathList(mCurrentPath, mCurrentSelectedItem, false, mIsRoot);
	}
	
	private static final int SETTING_ACTIVITY = 1024;
	private void setting_setting() {
		Intent intent = new Intent(this, SettingActivity.class);
		startActivityForResult(intent, SETTING_ACTIVITY);
//		CremaDialog dialog = new CremaDialog(this, CremaDialog.TYPE_INPUT, 
//				getResources().getString(R.string.alert),
//				getResources().getString(R.string.rename_dialog_message),
//				new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//		});
//		dialog.show(getSupportFragmentManager(), "dialog fragment");
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETTING_ACTIVITY)
        	getPrefLoading(false);
    }
	
	private void getPrefLoading(boolean bFirstLoading) {
		SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(CremaActivity.this);
		
		//language set
		String lang = myPref.getString(getResources().getString(R.string.pref_key_lang), null);
		updateLanguage(this, lang);
		if (! bFirstLoading) {
			restartActivity();
		}
		
		if (bFirstLoading) {
			// saved folder set
			Boolean bSavedFolder = myPref.getBoolean(getResources().getString(R.string.pref_key_last_folder), false);
			if (bSavedFolder) {
				String path = myPref.getString(getResources().getString(R.string.pref_key_last_folder_path), null);
				if (path != null) 
					mCurrentPath = new DirFileEntry(new File(path));
			}
			
		}
	}
	
	private void getPrefFavorite() {
		SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(CremaActivity.this);
		
		String favorite_serialized = myPref.getString(getResources().getString(R.string.pref_key_favorite_list), null);
		if (favorite_serialized != null) {
			List<String> savedList = Arrays.asList(TextUtils.split(favorite_serialized, ","));
			for (String item : savedList) {
				mNavigationDrawerFragment.favoriteListAdd(item);
			}
		}
		
	}
	
	private void savePref() {
		SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(CremaActivity.this);
		boolean bLastFolder = myPref.getBoolean(getResources().getString(R.string.pref_key_last_folder), false);
		
		Editor editor = myPref.edit();
		editor.putString(getResources().getString(R.string.pref_key_favorite_list), mNavigationDrawerFragment.favoriteListString());
		
		if (bLastFolder) {
			editor.putString(getResources().getString(R.string.pref_key_last_folder_path), mCurrentPath.getAbsolutePath());
		}
		
		editor.commit();
	}
	
	/**
	 * mount sdcard ..etc..
	 */
	BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (mNavigationDrawerFragment != null) {
				mNavigationDrawerFragment.rescanDirectories();
			}
		}
		
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// shared preference get..
		getPrefLoading(true);

		setContentView(R.layout.layout_main);

		
		mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		mTitle = getTitle();
		getSupportActionBar().setLogo(R.drawable.folder_01);
		
//		View v = getLayoutInflater().inflate(R.layout.actionbar_idle, null);
//		
//		ActionBar ab = getSupportActionBar();
//		ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
////		ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_SHOW_CUSTOM);
//		ab.setCustomView(v);
////		ab.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
////		ab.setDisplayShowTitleEnabled(true);
////		ab.setTitle(mTitle);
////		ab.setDisplayHomeAsUpEnabled(true);
		
		//설정화면
		settingView = (SlideAnimationLayout) findViewById(R.id.layout_settings);
		View slideView = (View) settingView.findViewById(R.id.layout_settingButtons);
		settingView.createAnimation();
		settingMenuInitialize(slideView);
		settingView.setVisibility(View.GONE);
		settingView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				settingView.setVisibility(View.GONE);
			}
			
		});
		
//		FrameLayout container = (FrameLayout) findViewById(R.id.container);
//		View rootView = inflater.inflate(R.layout.fragment_main, null);
//		container.addView(rootView);
//		
//		settingView = rootView.findViewById(R.id.layout_settings);
//		SlideAnimationLayout slideView = (SlideAnimationLayout) settingView.findViewById(R.id.layout_settingButtons);
//		slideView.createAnimation();
//		settingMenuInitialize(slideView);
//
//		
//		mMainGrid = (GridView) rootView.findViewById(R.id.layout_grid);
//		List<FileListEntry> files = FileLister.getFileLists(mCurrentPath, false);
//		
//		if (files != null) {
//			Collections.sort(files, new FileSorter(this, true, FileSorter.SORT_BY_NAME_ASC));
//		}
//		
//		mFileAdapter = new FileListAdapter(this, files);
//		mMainGrid.setAdapter(mFileAdapter);
//		mMainGrid.setOnItemClickListener(new OnItemClickListener() {
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				// TODO Auto-generated method stub
//			}
//        });

		
		
		// Start Service
		Intent intent = new Intent("com.cremamobile.filemanager.IRemoteService");
//		bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
		
//		Intent intent = new Intent("kr.letsnow.crema.service.IRemoteService");
		startService(intent);
		
		// receier 등록
	    registerReceiver(mReceiver, FileUtils.getRescanIntentFilter());
		
		mSelectedItem = new ArrayList<FileListEntry>();
		mDeviceList = FileLister.getDevices(getApplicationContext());
		
		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));
		
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager
				.beginTransaction()
				.replace(R.id.container,
						PlaceholderFragment.newInstance(1)).commit();

		restoreActionBar();
		
		if (mIsFirstLoadFolder) {
			mNavigationDrawerFragment.openDrawer();
			onNavigationDrawerOpened();
			
			mIsFirstLoadFolder = false;
		}

		// getting favorite saved data
		getPrefFavorite();
	}

	@Override
	public void onStart() {
		super.onStart();
//		EasyTracker.getInstance(this).activityStart(this);
	}
	
	@Override
	public void onStop() {
		super.onStop();
		
//		EasyTracker.getInstance(this).activityStop(this);
	}
	  
	@Override
	protected void onDestroy() {
		// Stop Service
//		if (mBound)
//			unbindService(mServiceConnection);
		
		this.unregisterReceiver(mReceiver);
		
		savePref();
		Intent intent = new Intent("com.cremamobile.filemanager.IRemoteService");
		stopService(intent);
		
		//
		super.onDestroy();
	}
	
	@Override
	public void onNavigationDrawerItemSelected(long position, String path) {
		// update the main content by replacing fragments
//		FragmentManager fragmentManager = getSupportFragmentManager();
//		fragmentManager
//				.beginTransaction()
//				.replace(R.id.container,
//						PlaceholderFragment.newInstance(position + 1)).commit();
		
		sendEventTrakcer("Drirectory Tree", "Directory Clicked");
		
		mNeedUpdateNavigationDrawer = false;
		
		mCurrentSelectedItem = 0;
		gettingCurrentPathList(new DirFileEntry(new File(path)), mCurrentSelectedItem, true);
		

	}

	@Override
	public void onNavigationDrawerOpened() {
		// TODO Auto-generated method stub
		mViewModeButton.setEnabled(false);
		mDeleteButton.setEnabled(false);
		mSettingButton.setEnabled(false);
		
		sendEventTrakcer("Drirectory Tree", "Opened");
	}

	@Override
	public void onNavigationDrawerClosed() {
		// TODO Auto-generated method stub
		mViewModeButton.setEnabled(true);
		mDeleteButton.setEnabled(true);
		mSettingButton.setEnabled(true);
		
		sendEventTrakcer("Drirectory Tree", "Closed");
	}

	public void gettingCurrentPathList(FileListEntry path, int currentIndex, boolean bHistory, boolean isRoot) {
		if (path == null)
			return;
		
		mIsRoot = isRoot;
		new Lister(this, new FileSorter(this, mDirOnTop, mSortType), currentIndex, bHistory, mIsRoot).execute(path);
	}
	
	public void gettingCurrentPathList(FileListEntry path, int currentIndex, boolean bHistory) {
		gettingCurrentPathList(path, currentIndex, bHistory, isRootPath(path.getAbsolutePath()));
	}
	
	public DeviceFileEntry getDeviceFromPath(String path) {
		if (mDeviceList == null) {
			return null;
		}
		
		for (FileListEntry item : mDeviceList) {
			DeviceFileEntry device = (DeviceFileEntry) item;
			if ( device.isContainPath(path) )
				return device;
		}
		
		return null;
	}
	
	public void bottomBarSet(List<FileListEntry> items) {
		int count = 0;
		if (items != null && items.size() > 0) {
			count = items.size();
			if ( ((FileListEntry)items.get(0)).isNavigationEntry() ) {
				count --;
			}
		}
		
		bottomBarSet(getResources().getString(R.string.bottom_all_count, count), "");
	}
	
	public void bottomBarSet(String countMessage, String selectMessage) {
		TextView allCountView = (TextView) mBottomBarView.findViewById(R.id.selected_count);
		allCountView.setText(countMessage);
		
		TextView sizeView = (TextView) mBottomBarView.findViewById(R.id.selected_size);
		sizeView.setText(selectMessage);
	}
	
	public static void changeBottomBarSelectedText(Context context, List<FileListEntry> selected) {
		TextView sizeView = (TextView) mBottomBarView.findViewById(R.id.selected_size);
		long totalSize = 0;
		int count = 0;
		String work = null;
		switch (mWorkMode) {
		case WORK_MODE_COPY:
			work = context.getResources().getString(R.string.copy);
			break;
		case WORK_MODE_MOVE:
			work = context.getResources().getString(R.string.move);
			break;
		case WORK_MODE_DELETE:
			work = context.getResources().getString(R.string.delete);
			break;
		default:
			work = "";
			break;
		}
		if (selected != null) {
			count = selected.size();
			for (FileListEntry entry : selected) {
				totalSize += entry.getSize();
			}
		}
		sizeView.setText(context.getResources().getString(R.string.bottom_selected_info, 
				count,
				work,
				FileUtils.formatSize(totalSize)));
	}
	
	public void restoreBottomBarSize() {
		TextView sizeView = (TextView) mBottomBarView.findViewById(R.id.selected_size);
		sizeView.setText("");
	}
	
	// TODO. grid, list 를 눌러서 온 경우는 이전 path에서 하나만 추가된 것이므로
	//  기존을 유지하고 뒤에 추가된 path만 TextView 를 생성하는 방식으로 수정
	public void pathTextSet(FileListEntry path, DeviceFileEntry device, boolean isRoot) {
		mPathTextView.removeAllViews();
		
		if (isRoot) {
			TextView tv = new TextView(this);
			tv.setBackgroundResource(R.drawable.background_toolbar_path_text);
			if (device.isExternalDevice()) {
				tv.setText(R.string.path_external);
			} else {
				tv.setText(R.string.path_internal);
			}
			mPathTextView.addView(tv);

		} else {
			final OnClickListener pathTextClickListner = new OnClickListener() {
	
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String path = (String) v.getTag();
					if (path != null) {
						mNeedUpdateNavigationDrawer = true;
						
						gettingCurrentPathList(new DirFileEntry(new File(path)), 0, false);
					}
				}
			};
			
			String curPath = device.removeDevicePath(path.getAbsolutePath());
			String[] seperatePath = curPath.split("/");
			if (seperatePath == null)
				return;
			
			StringBuffer currentpath = new StringBuffer();
			for (int i=0 ; i < seperatePath.length ; i++) {
				if (i == 0) {
					currentpath.append(device.getAbsolutePath());
				} else {
					currentpath.append("/" + seperatePath[i]);
				}
				
				if (i > 0) {
					TextView tv = new TextView(this);
					tv.setClickable(true);
					tv.setOnClickListener(pathTextClickListner);
					tv.setBackgroundResource(R.drawable.background_toolbar_path_text);
					if (i == 1) {
						tv.setText(seperatePath[i] );
					} else {
						tv.setText(" > " + seperatePath[i] );
					}
					tv.setTag(currentpath.toString());
					
					mPathTextView.addView(tv);
				}
			}
			
			mPathTextViewScroller.postDelayed(new Runnable() {
			    public void run() {
			    	mPathTextViewScroller.fullScroll(HorizontalScrollView.FOCUS_RIGHT);
			    }
			}, 100L);
		}
	}
	
	public void deviceImageSet(FileListEntry path, DeviceFileEntry device) {
		if ( device.isExternalDevice() ) {
			mDeviceImageView.setImageResource(R.drawable.tep_02_off);
		} else {
			mDeviceImageView.setImageResource(R.drawable.tep_01_off);
		}
	}
	
	public void favoriteImageSet(boolean bSet) {
		if (bSet) {
			mFavoriteImageView.setImageResource(R.drawable.tep_03_off_select);
		} else {
			mFavoriteImageView.setImageResource(R.drawable.tep_03_off);			
		}
	}
	
	public void onSectionAttached(int number) {
		mTitle = getString(R.string.app_name);
//		switch (number) {
//		case 1:
//			mTitle = getString(R.string.title_section1);
//			break;
//		case 2:
//			mTitle = getString(R.string.title_section2);
//			break;
//		case 3:
//			mTitle = getString(R.string.title_section3);
//			break;
//		}
	}

	public void restoreActionBar() {
		ActionBar ab = getSupportActionBar();

		ab.setDisplayShowCustomEnabled(true);
		ab.setDisplayShowTitleEnabled(false);
		ab.setDisplayShowHomeEnabled(true);
		ab.setDisplayHomeAsUpEnabled(true); // ActionBar Up 버튼이 표시됨.
		
		if (mActionbarNormal == null)
			mActionbarNormal = getLayoutInflater().inflate(R.layout.actionbar_idle, null);
		ab.setCustomView(mActionbarNormal);
		
		// actionbar의 버튼을 연결한다. -> 버튼에 따라 이미지 변경을 위해
		mViewModeButton = (Button) mActionbarNormal.findViewById(R.id.actionbar_viewmode);
		mDeleteButton = (Button) mActionbarNormal.findViewById(R.id.actionbar_delete);
		mSettingButton = (Button) mActionbarNormal.findViewById(R.id.actionbar_settings);
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		if (!mNavigationDrawerFragment.isDrawerOpen()) {
//			// Only show items in the action bar relevant to this screen
//			// if the drawer is not showing. Otherwise, let the drawer
//			// decide what to show in the action bar.
//			getMenuInflater().inflate(R.menu.crema, menu);
//			restoreActionBar();
//			return true;
//		}
//		return super.onCreateOptionsMenu(menu);
//	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
//		int id = item.getItemId();
//		if (id == R.id.action_settings) {
//			settingView.setVisibility(View.GONE);
//		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";

		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static PlaceholderFragment newInstance(int sectionNumber) {
			PlaceholderFragment fragment = new PlaceholderFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			fragment.setArguments(args);
			return fragment;
		}

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);

			///////////////
			//toolbar
			mPathTextViewScroller = (HorizontalScrollView) rootView.findViewById(R.id.path_view_scroller);
			mPathTextView = (LinearLayout) rootView.findViewById(R.id.path_view);
			mDeviceImageView = (ImageView) rootView.findViewById(R.id.device_image);
			mFavoriteImageView = (ImageView) rootView.findViewById(R.id.favorite_image);
			mBottomBarView = (LinearLayout) rootView.findViewById(R.id.layout_bottombar);
			
			////////////test...
			if (mCurrentPath == null) {
				if (mDeviceList != null)
					mCurrentPath = new DirFileEntry(((FileListEntry)(mDeviceList.get(0))).getPath());
			}
			mCurrentSelectedItem = 0;
			
			mMainGrid = (GridView) rootView.findViewById(R.id.layout_grid);
			mMainList = (ListView) rootView.findViewById(R.id.layout_list);
			
			mNeedUpdateNavigationDrawer = true;
			
			((CremaActivity)getActivity()).gettingCurrentPathList(mCurrentPath, mCurrentSelectedItem, true);
			
			OnItemClickListener mainListener = new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					
					mCurrentSelectedItem = position;
					
					if (mFileAdapter.isSelectMode() && mWorkMode != WORK_MODE_NORMAL) {
						FileListEntry selected = (FileListEntry)mFileAdapter.getItem(mCurrentSelectedItem);
						
						if (mWorkMode == WORK_MODE_SHARE) {
							// 하나만 아이템을 선택하도록 한다.
							if (mFileAdapter.beforeSelectedIndex() != mFileAdapter.NOT_SET)
								mFileAdapter.toggleSelect(mFileAdapter.beforeSelectedIndex());
							mFileAdapter.toggleSelect(mCurrentSelectedItem);
							
							mSelectedItem.clear();
							mSelectedItem.add(selected);
						} else if (mWorkMode == WORK_MODE_RENAME) {
							mSelectedItem.add(selected);
							((CremaActivity)getActivity()).rename();
						} else {
							// 복수개를 계속 선택하도록 한다.
							mFileAdapter.toggleSelect(mCurrentSelectedItem);
							if (mSelectedItem.contains(selected))
								mSelectedItem.remove(selected);
							else
								mSelectedItem.add(selected);
							changeBottomBarSelectedText(getActivity(), mSelectedItem);
						} 
					} else {
						// TODO Auto-generated method stub
						FileListEntry item = (FileListEntry) mFileAdapter.getItem(mCurrentSelectedItem);
						if (item.isDir()) {
							mNeedUpdateNavigationDrawer = true;
							
							((CremaActivity)getActivity()).gettingCurrentPathList(item, 0, item.isNavigationEntry() ? false:true);
						} else {
							//파일 실행
//							executeMediaFile(getActivity(), item);
//							executeMediaFileFromExt(getActivity(), item);
							executeMediaFileFromWebkitMap(getActivity(), item);
						}
					}
					
					
				}
            };
            
			mMainGrid.setOnItemClickListener(mainListener);
			mMainList.setOnItemClickListener(mainListener);
			
            // 현재는 무조건 Grid 만 처음에 표시하도록 되어 있으나,  TODO. save 상태에 따라 표시하도록 횐다.
            mViewMode = FileListAdapter.VIEW_MODE_LIST;
            ((CremaActivity)getActivity()).toggleViewMode();

//            // favorite도 setting 한다.
//    		mNavigationDrawerFragment.setFavoriteList(mFavoriteList);
			return rootView;
		}

		@Override
		public void onAttach(Activity activity) {
			super.onAttach(activity);
			((CremaActivity) activity).onSectionAttached(getArguments().getInt(
					ARG_SECTION_NUMBER));
		}
	}
	
	public static void executeMediaFile(Context context, FileListEntry item) {
		String extension = MimeTypeMap.getFileExtensionFromUrl(item.getAbsolutePath());
		String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
		
		Intent fileLinkIntent = new Intent(Intent.ACTION_EDIT);
		fileLinkIntent.addCategory(Intent.CATEGORY_DEFAULT);
		Uri uri = Uri.fromFile(item.getPath());
		fileLinkIntent.setDataAndType(Uri.fromFile(item.getPath()),
				mimeType);
		
		PackageManager pm = context.getPackageManager();
		List<ResolveInfo> list = pm.queryIntentActivities(fileLinkIntent,
				PackageManager.GET_META_DATA);
		if (list.size() == 0) {
			Toast.makeText(context, R.string.toast_none_exsit_program, Toast.LENGTH_SHORT).show();
		} else {
			context.startActivity(fileLinkIntent);
		}
		
	}

	public static void executeMediaFileFromWebkitMap(Context context, FileListEntry item) {
		Intent fileLinkIntent = new Intent(Intent.ACTION_VIEW);
		fileLinkIntent.addCategory(Intent.CATEGORY_DEFAULT);
		Uri uri = Uri.fromFile(item.getPath());

	    String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(uri.toString());
	    String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
	    
	    CLog.d("CremaActivity", "executeMediaFile : file["+item.getAbsolutePath() + "]");
	    CLog.d("CremaActivity", "executeMediaFile : ext["+extension + "], mimeType["+mimetype+"]");
	    
	    if (extension != null && mimetype != null) {
	    	fileLinkIntent.setDataAndType(uri, mimetype);
	    	
			PackageManager pm = context.getPackageManager();
			List<ResolveInfo> list = pm.queryIntentActivities(fileLinkIntent, PackageManager.GET_META_DATA);
			if (list.size() == 0) {
				Toast.makeText(context, R.string.toast_none_exsit_program, Toast.LENGTH_SHORT).show();
			} else {
				context.startActivity(fileLinkIntent);
			}
	    } else {
			Toast.makeText(context, R.string.toast_none_exsit_program, Toast.LENGTH_SHORT).show();
	    }
	}
	
	public static void executeMediaFileFromExt(Context context, FileListEntry item) {
		Intent fileLinkIntent = new Intent(Intent.ACTION_VIEW);
		fileLinkIntent.addCategory(Intent.CATEGORY_DEFAULT);
		Uri uri = Uri.fromFile(item.getPath());
		//확장자 구하기
		String fileExtend = item.getExt();
		// 파일 확장자 별로 mime type 지정해 준다.
		if (fileExtend.equalsIgnoreCase("mp3")) {
			fileLinkIntent.setDataAndType(uri, "audio/*");
		} else if (fileExtend.equalsIgnoreCase("mp4")) {
			fileLinkIntent.setDataAndType(uri, "vidio/*");
		} else if (fileExtend.equalsIgnoreCase("jpg")
				|| fileExtend.equalsIgnoreCase("jpeg")
				|| fileExtend.equalsIgnoreCase("gif")
				|| fileExtend.equalsIgnoreCase("png")
				|| fileExtend.equalsIgnoreCase("bmp")) {
			fileLinkIntent.setDataAndType(uri, "image/*");
		} else if (fileExtend.equalsIgnoreCase("txt")) {
			fileLinkIntent.setDataAndType(uri, "text/*");
		} else if (fileExtend.equalsIgnoreCase("doc")
				|| fileExtend.equalsIgnoreCase("docx")) {
			fileLinkIntent.setDataAndType(uri, "application/msword");
		} else if (fileExtend.equalsIgnoreCase("xls")
				|| fileExtend.equalsIgnoreCase("xlsx")) {
			fileLinkIntent.setDataAndType(uri,
					"application/vnd.ms-excel");
		} else if (fileExtend.equalsIgnoreCase("ppt")
				|| fileExtend.equalsIgnoreCase("pptx")) {
			fileLinkIntent.setDataAndType(uri,
					"application/vnd.ms-powerpoint");
		} else if (fileExtend.equalsIgnoreCase("pdf")) {
			fileLinkIntent.setDataAndType(uri, "application/pdf");
		} else if (fileExtend.equalsIgnoreCase("hwp")) {
			fileLinkIntent.setDataAndType(uri,
					"application/haansofthwp");
		} else {
			fileLinkIntent.setDataAndType(uri, "application/*");
		}
		PackageManager pm = context.getPackageManager();
		List<ResolveInfo> list = pm.queryIntentActivities(fileLinkIntent,
				PackageManager.GET_META_DATA);
		
		if (list.size() == 0) {
			Toast.makeText(context, R.string.toast_none_exsit_program, Toast.LENGTH_SHORT).show();
		} else {
			context.startActivity(fileLinkIntent);
		}
	}
	
	/*************************************************************************************************/
	// 공통 Handler
    private Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                default:
                    super.handleMessage(msg);
            }
        }

    };
    
	/*************************************************************************************************/
	// Service 
//	CremaFileService mService;
//	boolean			mBound;
//	
//	private ServiceConnection	mServiceConnection = new ServiceConnection() {
//
//		@Override
//		public void onServiceConnected(ComponentName name, IBinder service) {
//			// TODO Auto-generated method stub
//			CremaFileBinder binder = (CremaFileBinder) service;
//			mService = binder.getService();
//			mBound = true;
//			
//			//test!!!!!!!!!
//			mService.showToast("bind success!!!");
//		}
//
//		@Override
//		public void onServiceDisconnected(ComponentName name) {
//			// TODO Auto-generated method stub
//			mBound = false;
//			
//		}
//		
//	};

	// Remote Service
	private IRemoteService	mService = null;
	boolean	mBound = false;
	private IRemoteServiceCallback mServiceCallback = new IRemoteServiceCallback.Stub() {
		public void MessageCallback(int msg) {
			mHandler.sendEmptyMessage(msg);
		}
	};
	
	private ServiceConnection	mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mService = IRemoteService.Stub.asInterface(service);
			mBound = true;
			try {
				mService.registerCallback(mServiceCallback);
			} catch(RemoteException e) {
				// TODO... 
				
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			mService = null;
			mBound = false;
		}
		
	};
	
	/*************************************************************************************************/
	
	public static void updateLanguage(Context ctx, String lang)
	{
		if (lang == null)
			return;
		
		if (lang.equals("ko") || lang.equals("en")) {
			Configuration cfg = new Configuration();
			if (!TextUtils.isEmpty(lang))
				cfg.locale = new Locale(lang);
			else
				cfg.locale = Locale.getDefault();
			
			ctx.getResources().updateConfiguration(cfg, null);
		}
	}
	
	class ExternalMountBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
	        if (action.equals("android.intent.action.MEDIA_MOUNTED")) {
	            // react to event
	        	//TODO!!!
	        }
		}
		
	};
	
	/*****************************************************************************************************/
	public boolean setCurrentViewPerPath(FileListEntry path, List<FileListEntry> childs, int currentPosition, boolean saveHistory, boolean isRoot) {
		//TODO.
//		int pos = gridview.getFirstVisiblePosition(); 
//		gridview.smoothScrollToPosition(currentPosition);
		if (saveHistory) {
			// 현재 화면을 History에 넣는다.
			pushHistory(mCurrentPath, mCurrentSelectedItem);
		}
		
		mCurrentPath = path;
		if (childs == null) {
			// 파일 존재하지 않음.. TODO
			mFileAdapter.setList(new ArrayList<FileListEntry>());
			mCurrentSelectedItem = 0;
		} else {
			mFileAdapter.setList(childs);
			mCurrentSelectedItem = currentPosition;
		}
		
		DeviceFileEntry device = getDeviceFromPath(path.getAbsolutePath());
		bottomBarSet(childs);
		pathTextSet(mCurrentPath, device, isRoot);
		deviceImageSet(mCurrentPath, device);
		favoriteImageSet(mNavigationDrawerFragment.isExistFavorite(mCurrentPath.getAbsolutePath()));
		
		if (mNeedUpdateNavigationDrawer) {
			mNavigationDrawerFragment.selectItemForMainView(device, mCurrentPath);
		}
		return true;
	}
	
	@Override
	public void onBackPressed() {
		if (mNavigationDrawerFragment.isDrawerOpen()) {
			mNavigationDrawerFragment.closeDrawer();
			return;
		}
		
		if (settingView != null && settingView.getVisibility() == View.VISIBLE) {
			settingView.setVisibility(View.GONE);
			return;
		}
		
		if ( !backHistory() ) {
			
			long tempTime = System.currentTimeMillis();
			long intervalTime = tempTime - backPressedTime;
			
			if (0 <= intervalTime && FINISH_INTERVAL_TIME >= intervalTime) {
				backPressedTime = 0;
				super.onBackPressed();
			} else {
				backPressedTime = tempTime;
				Toast.makeText(this, R.string.toast_back_pressed, Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private boolean backHistory() {
		if (mHistoryStack == null || mHistoryStack.isEmpty()){
			return false;
		}
		
		HistoryNode history = mHistoryStack.peek();
		if (history.getPath() != null && !history.getPath().equals(mCurrentPath)) {
			mNeedUpdateNavigationDrawer = true;
			
			gettingCurrentPathList(history.getPath(), history.getCurrentPosition(), false);
			mHistoryStack.pop();
			
			return true;
		}
		return false;
	}
	
	private static void pushHistory(FileListEntry path, int selected) {
		
		if (mHistoryStack == null) {
			mHistoryStack = new Stack<HistoryNode>();
		}
		
		// 마지막 History가 현재 화면과 같으면 history에 넣지 않는다.
		HistoryNode peek = null;
		
		if (mHistoryStack.size() > 1) {
			peek = mHistoryStack.peek();
		}
		if (peek == null || ! peek.getPath().equals(path)) { 
			HistoryNode currentHistory = new HistoryNode(path, selected);
			mHistoryStack.push(currentHistory);
		}
	}
	
	private void settingMenuInitialize(View container) {
		Button settingButton = (Button) container.findViewById(R.id.setting_copy);
		settingButton.setOnClickListener(settingMenuClickListener);
		
		settingButton = (Button) container.findViewById(R.id.setting_move);
		settingButton.setOnClickListener(settingMenuClickListener);
		
		settingButton = (Button) container.findViewById(R.id.setting_rename);
		settingButton.setOnClickListener(settingMenuClickListener);
		
		settingButton = (Button) container.findViewById(R.id.setting_newfolder);
		settingButton.setOnClickListener(settingMenuClickListener);

		settingButton = (Button) container.findViewById(R.id.setting_sort);
		settingButton.setOnClickListener(settingMenuClickListener);

		settingButton = (Button) container.findViewById(R.id.setting_share);
		settingButton.setOnClickListener(settingMenuClickListener);
		
		settingButton = (Button) container.findViewById(R.id.setting_refresh);
		settingButton.setOnClickListener(settingMenuClickListener);

		settingButton = (Button) container.findViewById(R.id.setting_setting);
		settingButton.setOnClickListener(settingMenuClickListener);
	}
	
//	public static void buttonEffect(View button){
//	    button.setOnTouchListener(new OnTouchListener() {
//
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				// TODO Auto-generated method stub
//	            switch (event.getAction()) {
//                case MotionEvent.ACTION_DOWN: {
//                    v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
//                    v.invalidate();
//                    break;
//                }
//                case MotionEvent.ACTION_UP: {
//                    v.getBackground().clearColorFilter();
//                    v.invalidate();
//                    break;
//                }
//				return false;
//			}
//			}
//	    });
//	    
//	}
	
	private void toggleNavigationDrawer() {
		if (mNavigationDrawerFragment == null)
			return;
		
		if (mNavigationDrawerFragment.isDrawerOpen())
			mNavigationDrawerFragment.closeDrawer();
		else
			mNavigationDrawerFragment.openDrawer();
	}
	
	private void toggleViewMode() {
		List<FileListEntry> files = null;
		if (mFileAdapter != null) {
			files = mFileAdapter.getList();
		}
		
		if (mViewMode == FileListAdapter.VIEW_MODE_GRID) {
			mViewMode = FileListAdapter.VIEW_MODE_LIST;
			
			mMainGrid.setVisibility(View.GONE);
			mMainList.setVisibility(View.VISIBLE);
			
			mFileAdapter = new FileListAdapter(getApplicationContext(), files);
			mFileAdapter.setViewMode(mViewMode);
			mMainList.setAdapter(mFileAdapter);

			mViewModeButton.setBackgroundResource(R.drawable.button_actionbar_viewmode_grid);
		} else {
			mViewMode = FileListAdapter.VIEW_MODE_GRID;

			mMainGrid.setVisibility(View.VISIBLE);
			mMainList.setVisibility(View.GONE);

			mFileAdapter = new FileListAdapter(getApplicationContext(), files);
			mFileAdapter.setViewMode(mViewMode);
			mMainGrid.setAdapter(mFileAdapter);
			
			mViewModeButton.setBackgroundResource(R.drawable.button_actionbar_viewmode_list);
		}
	}
	
	private void closeOptionSetting() {
		if (settingView == null)
			return;
		
		if (settingView.getVisibility() == View.VISIBLE) {
			settingView.setVisibility(View.GONE);
		}
	}
	
	private void toggleOptionSetting() {
		
//		Animation slide = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down);
//		iew.startAnimation(slide);
		
		if (settingView == null)
			return;
		
		if (settingView.getVisibility() == View.VISIBLE) {
			settingView.setVisibility(View.GONE);
		} else {
			settingView.setVisibility(View.VISIBLE);
		}
	}

	private void toggleFavorite(FileListEntry path) {
		String absPath = path.getAbsolutePath();
		boolean bContains = mNavigationDrawerFragment.isExistFavorite(absPath);
		
		if ( ! bContains) {
			if (mNavigationDrawerFragment.favoriteListSize() >= FAVORITE_MAX_SIZE) {
				Toast.makeText(this, getString(R.string.favorite_full_dialog_message, FAVORITE_MAX_SIZE), Toast.LENGTH_SHORT).show();
				return;
			}
			mNavigationDrawerFragment.favoriteListAdd(absPath);
			String toastString = getResources().getString(R.string.toast_favorite_set_success, mNavigationDrawerFragment.favoriteListSize());
			Toast.makeText(CremaActivity.this, toastString, Toast.LENGTH_SHORT).show();
		} else {
			
			mNavigationDrawerFragment.favoriteListRemove(absPath);
			String toastString = getResources().getString(R.string.toast_favorite_delete_success, mNavigationDrawerFragment.favoriteListSize()+1);
			Toast.makeText(CremaActivity.this, toastString, Toast.LENGTH_SHORT).show();
		}
		favoriteImageSet( ! bContains);
	}
	
	public void actionbar_clickListener(View v) {
		int id = v.getId();
		switch(id) {
		case R.id.actionbar_viewmode:
			closeOptionSetting();
			toggleViewMode();
			break;
		case R.id.actionbar_delete:
			closeOptionSetting();
			mWorkMode = WORK_MODE_DELETE;
			setWorkMode(true);
			break;
		case R.id.actionbar_settings:
			toggleOptionSetting();
			break;
		case R.id.actionbar_all_select:
			if (mWorkMode == WORK_MODE_PAUSE_COPY || mWorkMode == WORK_MODE_PAUSE_MOVE) {
				toggleNavigationDrawer();
			} else {
				mFileAdapter.toggleSelectAll();
			}
			break;
		case R.id.actionbar_cancel:
			restoreActionBar();
			restoreBottomBarSize();
			mFileAdapter.setSelectMode(false);
			mSelectedItem.clear();
			break;
		case R.id.actionbar_doing:
			{
				switch(mWorkMode) {
				case WORK_MODE_COPY:
					mWorkMode = WORK_MODE_PAUSE_COPY;
					setWorkMode(false);
					break;
				case WORK_MODE_MOVE:
					mWorkMode = WORK_MODE_PAUSE_MOVE;
					setWorkMode(false);
					break;
				case WORK_MODE_RENAME:
//					rename();
					break;
				case WORK_MODE_DELETE:
					delete();
					break;
				case WORK_MODE_SHARE:
					share();
					break;
				case WORK_MODE_PAUSE_COPY:
					copy();
					break;
				case WORK_MODE_PAUSE_MOVE:
					move();
					break;
				}
			}
			break;
		}
	}
	
	public void toolbar_clickListener(View v) {
		int id = v.getId();
		switch(id) {
		case R.id.device_image_parent:
		case R.id.device_image:
			{
				DeviceFileEntry device = getDeviceFromPath(mCurrentPath.getAbsolutePath());
				
				mNeedUpdateNavigationDrawer = true;
				gettingCurrentPathList(device, 0, true, true);
			}
			break;
		case R.id.favorite_image_parent:
		case R.id.favorite_image:
			toggleFavorite(mCurrentPath);
			break;
		}
	}

	public static boolean isRootPath(String path) {
		if (mDeviceList == null) {
			return false;
		}
		
		for (FileListEntry item : mDeviceList) {
			DeviceFileEntry device = (DeviceFileEntry) item;
			if ( device.getAbsolutePath().equals(path) )
				return true;
		}
		
		return false;
	}
	
	
	private void restartActivity() {
	    Intent intent = getIntent();
	    finish();
	    startActivity(intent);
	}

	
	public void onCreateTracker() {
		Tracker t = ((CremaApplication)getApplication()).getTracker(CremaApplication.TrackerName.APP_TRACKER);
		t.setScreenName("CremaActivity");
		t.send(new HitBuilders.AppViewBuilder().build());
	}
	
	public void onStartTracker() {
		GoogleAnalytics.getInstance(this).reportActivityStart(this);
	}
	
	public void onStopTracker() {
		GoogleAnalytics.getInstance(this).reportActivityStop(this);
		
	}
	
	public void sendEventTrakcer(String action, String label) {
		// Get tracker.
        Tracker t = ((CremaApplication)getApplication()).getTracker(CremaApplication.TrackerName.APP_TRACKER);
        t.send(new EventBuilder()
        		.setCategory("CremaActivity")
        		.setAction(action)
        		.setLabel(label)
        		.build());
        // Set screen name.
	}
}
